package handler.store.ind.peizi

import com.alibaba.fastjson.JSON

import service.wx.WxUserLocal
import service.wx.WxSignature
import service.wx.WxApi
import service.wx.WxPay

import org.vertx.groovy.core.buffer.Buffer

import org.paic.d.D

handler.get('/wx/pay/pz__:openid'){req, resp ->
	String openid = req.params.openid
	if(!openid){
		resp.end ''
		return
	}

	def user = WxUserLocal.getUserCached(openid)
	if(user.errcode){
		resp.render('/wx/ind/index-error.html', user)
		return
	}

	def userSaved = [:]
	userSaved.nickname = user.nickname
	userSaved.openid = user.openid
	userSaved.headimgurl = user.headimgurl

	Map r = [:]
	r.timeend = '' + System.currentTimeMillis()
	r.userSaved = JSON.toJSONString(userSaved)

	String ua = req.headers.get('User-Agent')
	boolean isWx = WxApi.isReqFromWx(ua)
	if(isWx){
		Map jsapiInfo = WxSignature.getJsapiInfo(WxSignature.conf.urlHost + req.uri)
		r.putAll(jsapiInfo)
	}

	resp.render('/wx/ind/peizi/index.html', r)
}

handler.get('/wx/pay/peizi-index'){req, resp ->
	String code = req.params.code
	if(!code){
		resp.render('/wx/ind/index-reject.html', [:])
		return
	}

	def info = WxSignature.getAccessTokenInfo4Auth(code)
	if(info.errcode){
		resp.render('/wx/ind/index-error.html', info)
		return
	}

	def user = WxApi.getUserInfo4Auth(info.access_token, info.openid)
	if(user.errcode){
		resp.render('/wx/ind/index-error.html', user)
		return
	}

	if(user.openid){
		WxUserLocal.update(user)
	}

	resp.redirect('/wx/pay/pz__' + user.openid + '?showwxpaytitle=1')
}

handler.get('/wx/ind/peizi/send-tel-verify-code'){req, resp ->
	String userTel = req.params.userTel
	if(!userTel){
		resp.json([flag: false, msg: 'parameter required'])
		return
	}

	def rand = new Random()
	String code = ''
	4.times{
		code += rand.nextInt(9)
	}

	log.info('verify code sended : ' + code + ' - ' + userTel)
	
	// TODO send sms

	req.session('tel-verify-code-time', new Long(System.currentTimeMillis()))
	req.session('tel-verify-code', code)
	resp.json([flag: true])
}

// 修改个人信息
handler.post('/wx/ind/peizi/update-user-info'){req, resp ->
	req.jsonHandler{json ->
		String type = json.type
		String openid = json.openid

		if(!openid || !type){
			resp.json([flag: false, msg: 'openid/type not given'])
			return
		}

		Map item = [:]
		item.openid = openid

		if('idcardNo' == type){
			item.idcardNo = json.idcardNo
		}else if('userName' == type){
			item.name = json.userName
		}else if('userTel' == type){
			item.tel = json.userTel

			// for test, not verify TODO
//			Long verifyCodeTime = req.session('tel-verify-code-time')
//			if(!verifyCodeTime || (verifyCodeTime + 120 * 1000) < System.currentTimeMillis()){
//				resp.json([flag: false, tips: 'verify-code-expired'])
//				return
//			}
//
//			String verifyCode = json.userTelVerifyCode
//			String code = req.session('tel-verify-code')
//
//			if(!code || code != verifyCode){
//				resp.json([flag: false, tips: 'verify-code-expired'])
//				return
//			}
		}else if('userId' == type){
			if(json.isPic2){
				item.idcardPic2 = json.serverId;
			}else{
				item.idcardPic = json.serverId;
			}
		}

		def d = D.gen()

		def user = d.queryMap('select id from t_peizi_user_info where openid = ?', [openid])
		if(user){
			item.id = user.id
			d.update(item, 't_peizi_user_info', null)
		}else{
			d.add(item, 't_peizi_user_info')
		}
	
		resp.json([flag: true])
	}
}

handler.get('/wx/ind/peizi/img-show'){req, resp ->
	String serverId = req.params.serverId
	if(!serverId){
		resp.statusCode = 404
		resp.end ''
		return
	}

	String localPath = config.webroot + '/wx/ind/peizi/img/' + serverId + '.jpg'
	def f = new File(localPath)

	resp.headers.set('Content-Type', 'image/jpg')

	if(f.exists()){
		vertx.fileSystem.readFile(localPath){ar ->
			if(ar.succeeded){
				resp.chunked = true
				resp << ar.result
				resp.end()
			}else{
				resp.setStatusCode(404).end()
			}
		}
	}else{
		def bytes = WxApi.downloadPic(serverId)
		if(bytes){
			log.info('download from weixin and save to local : ' + bytes.size())

			f.bytes = bytes

			resp.chunked = true
			resp << new Buffer(bytes)
			resp.end()
		}else{
			resp.setStatusCode(404).end()
		}
	}
}

handler.post('/wx/ind/peizi/apply'){req, resp ->
	req.jsonHandler{json ->
		int amount = json.amount
		int num = json.num
		int numMulti = json.numMulti
		// month day
		String type = json.type
		if('month' != type)
			type = 'day'

		String openid = json.openid
		if(!openid){
			resp.json([flag: false, msg: 'openid not given'])
			return
		}

		if(!amount || !num || !numMulti){
			resp.json([flag: false, tips: 'amount-required'])
			return
		}

		// max 5w
		if(amount <= 0 || amount > 5 * 10000){
			resp.json([flag: false, tips: 'amount-rangeout'])
			return
		}
		// 倍数1-5
		if(numMulti <= 0 || numMulti > 5){
			resp.json([flag: false, tips: 'multi-rangeout'])
			return
		}

		if(type == 'month'){
			// max 5 years
			if(num <= 0 || num > 50){
				resp.json([flag: false, tips: 'num-rangeout'])
				return
			}
		}else{
			// max 50 days
			if(num <= 0 || num > 50){
				resp.json([flag: false, tips: 'num-rangeout'])
				return
			}
		}

		// 计算利息，利率参数 TODO
		int intPerDayEveryWan = 12
		double intPerMonthPercent = 0.013

		int amountInt = 0
		if('month' == type){
			int intPerMonth = numMulti * amount * intPerMonthPercent
			if(intPerMonth == 0)
				intPerMonth = 1

			amountInt = intPerMonth * num
		}else{
			int wanNum = numMulti * amount / 10000
			if(wanNum == 0)
				wanNum = 1

			int intPerDay = wanNum * intPerDayEveryWan
			amountInt = intPerDay * num
		}
		int totalPay = amount + amountInt


		def d = D.gen()

		// 检查个人信息是否完整
		def user = d.queryMap('select * from t_peizi_user_info where openid = ?', [openid])
		if(!user || !user.tel || !user.idcardNo || !user.name){
			resp.json([flag: false, tips: 'person-info'])
			return
		}

		Map item = [:]
		item.amount = amount
		item.amountInt = amountInt
		item.totalPay = totalPay

		item.type = type
		item.num = num
		item.numMulti = numMulti
		item.openid = openid
		item.tradeNo = WxPay.generateNonce()
		
		log.info('' + item)

		d.add(item, 't_peizi_pay_order')

		String ua = req.headers.get('User-Agent')
		boolean isWx = WxApi.isReqFromWx(ua)

		if(isWx){
			def params = [:]

			params.openid = openid
			params.totalFee = totalPay * 100
			params.body = '配资支付'
			params.tradeNo = item.tradeNo
			// 随便一个ip
			params.ip = '8.8.8.8'

			def r = WxPay.genPostParams(params)
			String prepayId = WxPay.getPrepayId(r)

			if(!prepayId){
				resp.json([flag: false, tips: 'wx-order-failed'])
				return
			}

			def jsPayParams = WxPay.genPayJsParams(prepayId)
			jsPayParams.flag = true
			resp.json(jsPayParams)
		}else{
			resp.json([flag: true])
		}
	}
}

// 获取个人信息
handler.get('/wx/ind/peizi/get-user-info'){req, resp ->
	String openid = req.params.openid
	if(!openid){
		resp.json([flag: false, msg: 'parameter required'])
		return
	}

	def d = D.gen()
	def user = d.queryMap('select * from t_peizi_user_info where openid = ?', [openid])

	resp.json([flag: true, user: user])
}

// 获取订单
handler.get('/wx/ind/peizi/get-apply-list'){req, resp ->
	String openid = req.params.openid
	if(!openid){
		resp.json([flag: false, msg: 'parameter required'])
		return
	}

	def d = D.gen()

	// lasted 1
	def dd = new Date()
	def ll = d.query('select * from t_peizi_pay_order where openid = ? and dd > ? order by dd desc limit 5', 
		[openid, dd - 1])

	resp.json([ll: ll])
}